const { uploadFile, deleteFile, getFile, uploadFiles } = require('../services/uploadService');

const uploadFileController = async (ctx) => {
  try {
    const { fileId, chunkNumber, totalChunks } = ctx.request.body;
    const { file } = ctx.request.files

    // 调用上传服务的方法来处理文件上传逻辑
    const uploadedFile = await uploadFile(file, fileId, chunkNumber, totalChunks);

    ctx.body = { file: uploadedFile };
  } catch (error) {
    ctx.status = 500;
    ctx.body = { error: '文件上传失败。' };
  }
};

const deleteFileController = async (ctx) => {
  const { fileId } = ctx.params;
  try {
    await deleteFile(fileId);
    ctx.body = { message: '文件删除成功。' };
  } catch (error) {
    ctx.status = 500;
    ctx.body = { error: '文件删除失败。' };
  }
};

const getFileController = async (ctx) => {
  const { fileId } = ctx.params;
  try {
    const file = await getFile(fileId);
    if (file) {
      ctx.body = { file };
    } else {
      ctx.status = 404;
      ctx.body = { error: '文件不存在。' };
    }
  } catch (error) {
    ctx.status = 500;
    ctx.body = { error: '获取文件失败。' };
  }
};

const uploadBatchController = async (ctx) => {
  try {
    const { file } = ctx.request.files
    const { user } = ctx.state
    const res = await uploadFiles(file, user.id)

    // console.log(res);
    ctx.body = { files: res }
  } catch(error) {
    ctx.status = 500;
    ctx.body = { error: '文件上传失败。' };
  }
}

module.exports = { uploadFileController, deleteFileController, getFileController, uploadBatchController };
